<template>
    <view class="xilu">
        <view class="page-foot bg-white" @click="formSubmit()">
            <view class="btn1">立即发布</view>
        </view>
        <view class="container plr30 pt30">
            <view class="flex-box flex-between pb30">
                <view class="fs34 fwb">分类</view>
                <!-- <view class="fs24 col89">更多+</view> -->
            </view>
            <multi-select :items="categoryList" @change="bindCategoryChange" id_key="id" name_key="name" children_key="childlist" :value="product.category_id" ref="pickers">
                <view class="area flex-box m-arrow-right">
                    <view>分类</view>
                    <view class="fs30 cola flex-grow-1 tr" v-if="!selectedSecond">请选择</view>
                    <view class="fs30 cola flex-grow-1 tr" v-else> {{selectedFirst.name}} -
                        {{selectedSecond.name}}
                    </view>
                </view>
            </multi-select>
            <view class="ptb30 fs34 fwb">回收区域 <text class="fs24 normal pl20">可多选</text></view>
            <view class="area flex-box m-arrow-right" @tap.stop="cityPop=true">
                <view>省市</view>
                <view class="fs30 cola flex-grow-1 tr">{{Object.keys(areasIds).length>0?'已选择':'请选择'}}</view>
            </view>
            <view class="ptb30 fs34 fwb">图片</view>
            <u-upload :fileList="fileListimages" @afterRead="afterRead" @delete="deletePic" name="images" multiple :maxCount="10" width="210" height="210" :previewFullImage="true"></u-upload>
            <view class="ptb30 fs34 fwb">回收标题</view>
            <textarea class="xilu_text1 fs30" v-model="product.name" maxlength="50" placeholder="请输入商品标题" placeholder-class="colc"></textarea>
            <view class="ptb30 fs34 fwb">商品描述</view>
            <textarea class="xilu_text2 fs30" v-model="product.content" maxlength="600" placeholder="请输入商品描述" placeholder-class="colc"></textarea>
            <view class="flex-box pt30 pb50">
                <view class="flex-grow-1 fs34 fwb">商品价格</view>
                <view class="fs34 cola">¥</view>
                <input type="number" placeholder-class="cola" v-model="product.salesprice" class="fs34 xilu_input tr" placeholder="请输入">
            </view>
        </view>

        <u-popup :show="cityPop" mode="bottom" round="30" closeable closeOnClickOverlay @close="cityPop = false">
            <view class="pb50">
                <view class="fs34 col3 fwb tc ptb50">请选择区域</view>
                <view class="city_box flex-box">
                    <view class="list">
                        <!-- <view class="item active">省</view> -->
                        <view v-for="(item,index) in areas" class="item " @click="bindChooseProvince(index)" :class="(index==areasIndex?'active':'')">{{item.name}}</view>
                    </view>
                    <view class="list region">
                        <!-- <view class="item active">全部</view> -->
                        <view v-for="(item,index) in areas[areasIndex].childlist" @click="bindChooseCity(index)" class="item" :class="(item.check?'active':'')">{{item.name}}</view>
                    </view>
                </view>
                <view class="btn1 pop" @click="bindAreaSure()">确定提交</view>
            </view>
        </u-popup>
    </view>
</template>

<script>
    import multiSelect from '@/components/multi-select/multi-select.vue';
    var validate = require("../../xilu/validate.js");
    export default {
        data() {
            return {
                fileListimages: [],
                product: {
                    product_type: 2,
                    category_id: '',
					city_ids:[],
                    name: '',
                    content: '',
                    salesprice: ''
                },
                categoryList: [],
                selectedFirst: null,
                selectedSecond: null,
				areas:[{id:0,name:'全国',childlist:[{id:0,name:'全部'}]}],
				areasIndex:0,
				areasIds:{},
                cityPop: false,
            };
        },
        onLoad() {
            let page = this;
            this.getOpenerEventChannel().on('addProductTransfor', function(product) {
                if (Object.keys(product).length > 0) {
                    page.product = product;
                    let images = [];
                    product.images.forEach(item => {
                        images.push({
                            status: 'success',
                            message: '',
                            url: item
                        })
                    })
                    page.fileListimages = images;
                }
            })
            page.fetchCategoryList();
			this.$util.getAreaTree(false).then(areas=>{
				let new_areas = page.areas.concat(areas);
				let city_ids = page.product.city_ids;
				if(city_ids.length>0){
					for(let i=1;i<new_areas.length;i++){
						new_areas[i].count = 0;
						for(let k=0;k<new_areas[i].childlist.length;k++){
							if(city_ids.indexOf(new_areas[i].childlist[k].id) !== -1){
								new_areas[i].childlist[k].check = true;
								new_areas[i].count +=1;
								if(page.areasIds[new_areas[i].id]){
									page.areasIds[new_areas[i].id].push(new_areas[i].childlist[k].id)
								}else{
									page.areasIds[new_areas[i].id] = [new_areas[i].childlist[k].id];
								}
							}
							
						}
					}
				}
				page.areas = new_areas;
			})
        },
        methods: {
            //分类
            fetchCategoryList() {
                this.$core.get({url: 'xilumarket.product_category/lists',data: {},loading: false,success: ret => {
                        this.categoryList = ret.data;
                    }
                })
            },
            //分类选择
            bindCategoryChange(e) {
                let categoryIndex = e.indexValues;
                let categoryList = this.categoryList;
                this.product.category_id = categoryList[categoryIndex[0]].childlist[categoryIndex[1]].id;
                this.selectedFirst = {
                    id: categoryList[categoryIndex[0]].id,
                    'name': categoryList[categoryIndex[0]].name
                };
                this.selectedSecond = {
                    id: categoryList[categoryIndex[0]].childlist[categoryIndex[1]].id,
                    'name': categoryList[categoryIndex[0]].childlist[categoryIndex[1]].name
                };
            },
            // 删除图片
            deletePic(event) {
                this[`fileList${event.name}`].splice(event.index, 1)
            },
            // 新增图片
            async afterRead(event) {
                // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
                let lists = [].concat(event.file)
                let fileListLen = this[`fileList${event.name}`].length
                lists.map((item) => {
                    this[`fileList${event.name}`].push({
                        ...item,
                        status: 'uploading',
                        message: '上传中'
                    })
                })
                for (let i = 0; i < lists.length; i++) {
                    const result = await this.uploadFilePromise(lists[i].url)
                    let item = this[`fileList${event.name}`][fileListLen]
                    this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
                        status: 'success',
                        message: '',
                        url: result
                    }))
                    fileListLen++
                }
            },
            uploadFilePromise(filepath) {
                let page = this;
                return new Promise((resolve, reject) => {
                    page.$core.uploadFile({
                        filePath: filepath,
                        success: (ret, response) => {
                            resolve(ret.data.url)
                        }
                    })
                })
            },
			//切换省
			bindChooseProvince(index){
				this.areasIndex = index;
			},
			//选择市
			bindChooseCity(secondIndex){
				let firstIndex = this.areasIndex;
				let areas = this.areas;
				let city =  areas[firstIndex].childlist;
				city[secondIndex].check = city[secondIndex].check=='undefined' ? true : !city[secondIndex].check;
				if(city[secondIndex].id==0){
					//选择全省全部则取消其他选项
					for(let i=1;i<areas.length;i++){
						areas[i].count = 0;
						for(let k=0;k<areas[i].childlist.length;k++){
							areas[i].childlist[k].check = false;
						}
					}
				}else{
					let count = 0;
					for(let i=0;i<city.length;i++){
						if(city[i].check){
							count += 1;
						}
					}
					areas[0].childlist[0].check = false;
					areas[firstIndex].count = count;
					areas[firstIndex].childlist = city;
				}
				this.areas = areas;
				this.$forceUpdate();
			},
			bindAreaSure(){
				let areas = this.areas;
				let areasIds = {};
				for(let i=0;i<areas.length;i++){
					for(let j=0;j<areas[i].childlist.length;j++){
						if(areas[i].childlist[j].check){
							if(areasIds[areas[i].id]){
								areasIds[areas[i].id].push(areas[i].childlist[j].id)
							}else{
								areasIds[areas[i].id] = [areas[i].childlist[j].id];
							}
						}
					}
				}
				if(Object.keys(areasIds).length<=0){
					uni.showToast({title: '请选择城市',icon:'none'});
					return false;
				}
				this.areasIds = areasIds;
				this.cityPop = false;
			},
            //提交
            formSubmit() {
                let formData = this.product;
                console.log(formData);
				formData.areas_ids = this.areasIds;
                let images = []
                this.fileListimages.forEach(item => images.push(item.url));
                formData.images = images.join(',');
                var rule = [
					{name: 'category_id',nameChn: '分类',rules: ['require', 'gt:0'],errorMsg: {require: '请选择商品分类',gt: '请选择商品分类'},},
                    {name: 'name',nameChn: '商品标题',rules: ['require', 'length:1,50'],errorMsg: {require: '请填写商品标题',length: "标题限制50字"},},
                    {name: 'content',nameChn: '商品描述',rules: ['require', 'length:1,600'],errorMsg: {require: '请填写商品描述',length: "描述限制600字"},},
                    {name: 'salesprice',nameChn: '商品价格',rules: ['require', 'gt:0'],errorMsg: {require: '请填写商品价格',gt: "价格大于0"},}
                ];
                // 是否全部通过，返回Boolean
                //console.log(validate.check(formData,rule),validate.getError(),formData);

                if (!validate.check(formData, rule)) {
                    uni.showToast({
                        title: validate.getError()[0],
                        icon: 'none'
                    });
                    return;
                }
				if(Object.keys(formData.areas_ids).length<=0){
					uni.showToast({title: '请选择城市',icon:'none'});
					return false;
				}
                this.$core.post({
                    url: 'xilumarket.recovery/add',
                    data: formData,
                    success: ret => {
                        uni.showModal({
                            title: '提示',
                            content: '发布成功，等待审核',
                            showCancel: false,
                            success(res) {
                                uni.navigateBack({});
                            }
                        });
                    }
                })
            }
        }
    }
</script>

<style lang="scss" scoped>
    .xilu {
        &_target {
            padding: 0 18rpx;
            height: 70rpx;
            line-height: 70rpx;
            background-color: #F7F9FC;
            border-radius: 10rpx;
            margin-right: 20rpx;
            margin-bottom: 20rpx;

            &.active {
                background-color: #FFC100;
            }
        }

        &_text1 {
            width: 690rpx;
            height: 160rpx;
            background: #F7F9FC;
            border-radius: 20rpx;
            padding: 30rpx;
        }

        &_text2 {
            width: 690rpx;
            height: 470rpx;
            background: #F7F9FC;
            border-radius: 20rpx;
            padding: 30rpx;
        }

        &_input {
            width: 150rpx;
            padding-left: 30rpx;
        }

        .m-arrow-right:after {
            border-color: #aaa;
        }

        .area {
            width: 690rpx;
            height: 110rpx;
            background: #F7F9FC;
            border-radius: 20rpx;
            padding: 0 50rpx 0 30rpx;

            &::after {
                right: 30rpx;
            }
        }

        .normal {
            font-weight: normal;
        }

        .btn1.pop {
            width: 650rpx;
            height: 80rpx;
            line-height: 80rpx;
            background: #FFC100;
            border-radius: 40rpx;
            margin: 10rpx auto;
            color: #101010;
            font-size: 30rpx;
        }

        .city_box {
            height: 400rpx;

            .list {
                width: 180rpx;
                height: 100%;
                overflow-y: scroll;
                background: #F7F9FC;

                .item {
                    height: 80rpx;
                    line-height: 80rpx;
                    text-align: center;
                    position: relative;
                    font-size: 36rpx;
                }

                .item.active {
                    font-weight: bold;
                    color: #101010;
                }

                &.region {
                    flex: 1;
                    width: auto;
                    background: #fff;
                    border-radius: 0;
                    padding: 20rpx 20rpx 0;
                    display: flex;
                    flex-wrap: wrap;

                    .item {
                        width: 163rpx;
                        height: 70rpx;
                        margin-right: 20rpx;
                        margin-bottom: 30rpx;
                        background: #F7F9FC;
                        border-radius: 40rpx;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        color: #555;
                        font-size: 30rpx;

                        &:nth-of-type(3n) {
                            margin-right: 0;
                        }
                    }

                    .item.active {
                        background: #FFC100;
                        color: #333;
                        font-weight: normal;
                    }
                }
            }
        }
    }
</style>